package com.elinshaw.hadoopdev;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * /*
 * 指定Reducer<KEYIN, VALUEIN, KEYOUT, VALUEOUT>
 * 这4个类型分别为Text, IntWritable, Text, IntWritable，
 * 相当于普通类型string，int，string，int
 *
 * @author Administrator
 */
public class TestReducer extends Reducer<Text, LongWritable, Text, LongWritable> {

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        System.out.println("TestReducer is setup");
    }

    @Override
    public void run(Context context) throws IOException, InterruptedException {
        System.out.println("TestReducer is run");
        super.run(context);
    }


    /**
     * 将所有kv对缓存起来进行分组，然后传递一个组<key,value{}>，调用一次reduce方法
     * key对应单词，values的类型是一个迭代器（1,1,1,1,1,1）这种类型的数据
     */
    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
        long count = 0;
        //遍历value的list，进行累加求和
        for (LongWritable value : values) {
            count += value.get();
        }
        //输出这一个单词统计结果
        context.write(key, new LongWritable(count));
    }


    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        System.out.println("TestReducer is cleanup");
    }


}
